//配置接口url
var baseUrl = "https://wewefala.com/cdi_CenterData/getdata.jsp?sub_code=8A0731CC39614C90A5D474BC17253713&sub_usercode=414A6DB3BBE6419DA3768E6E25127310";
//业务接口url
var bizzUrl = "https://wewefala.com/cdi_CenterData/getdata.jsp?sub_code=FF0731CC39614C90A5D474BC17253713&sub_usercode=114A6DB3BBE6419DA3768E6E25127310";

//var baseUrl = "https://"+ getIP()+ ":8089/CenterData?sub_code=8A0731CC39614C90A5D474BC17253713&sub_usercode=414A6DB3BBE6419DA3768E6E25127310";
var session_id = "";
var login_id = "";
var nickname="";
var rid = 0;
var winWidth = 0, winHeight = 0;
var jsonTemplateIFaceLinkMenu = null;
var jsonTemplateIFaceLinkPage = null;
var jsonReadCommonRes = null;
var ly_index;
var is_history_back = 0;

//获取根目录
function getRootPath() {
    var curWwwPath = window.document.location.href;
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0, pos);
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    if (baseUrl.indexOf("getdata.jsp") != -1)
        return (localhostPath + projectName);
    else
        return localhostPath;
}

// 页面初始化权限判断
function init_page() {
    //获取session_id
    session_id = localStorage.getItem('session_id');
    if (session_id == null)
        session_id = "";
    login_id = localStorage.getItem('login_id');
    if (login_id == null)
        login_id = "";
    nickname = localStorage.getItem('nickname');
    if (nickname == null)
        nickname = "";
    rid = localStorage.getItem('rid');
    if (rid == null)
        rid = "";
    //判断服务端session_id是否超时
    T01_SELSSS();
}

// 获取页面参数
function getUrlParam(k) {
    var regExp = new RegExp('([?]|&)' + k + '=([^&]*)(&|$)');
    var result = window.location.href.match(regExp);
    if (result) {
        return decodeURIComponent(result[2]);
    } else {
        return null;
    }
}

//权限判断结果
function T01_SELSSS_Result(input) {
    data2 = input.T01_SELSSS;
    var s_result = "";
    var error_desc = "";
    for (var key in data2[0]) {
        if (key == 's_result') {
            s_result = data2[0].s_result;
            error_desc = data2[0].error_desc;
        }
    }
    if (s_result != "1") {
        window.location.href = "../main/login.html";
    } else {
		var inputdata = {param_name:"T01_sel_t_app_menu_bottom"};
		get_ajax_baseurl(inputdata,"init_result");
	}
}

//获取用户登录信息
function T01_SELSSS() {	
	var inputdata = {param_name:"T01_SELSSS",session_id: session_id};
	get_ajax_baseurl(inputdata,"T01_SELSSS_Result");
}

//获取当前页面名称
function getPageUrl(){
	 var str = window.location.pathname;
	 str = str.substr(str.lastIndexOf('/', str.lastIndexOf('/') - 1) + 1);
	 str = str.substr(0,str.lastIndexOf('.html', str.lastIndexOf('.html')));
	 str = str.replaceAll("/","_")+"_";
	 return str;
}

//replaceAll函数
String.prototype.replaceAll = function(old_str,new_str){
	if(old_str == "")
		return this;
	else
	{
		var strV = this;
		strV = strV.replace(old_str,new_str);
		while(strV.indexOf(old_str) != -1)
		{
			strV = strV.replace(old_str,new_str);
		}
		return strV;
	}
}

//时间格式化1
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//时间格式化2
function dateFmt(fmt, date) {
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//对应转换
function js_decode(s) {
    while (s.indexOf('+') >= 0)
        s = s.replaceAll("+","%20");//s.replace('+', '%20');
    return s;
}

//url 编码
function s_encode(s_result) {
    //python encodeURIComponent(s_result);
    //java   encodeURIComponent(s_result).replace(/%20/g,"+");
    return encodeURIComponent(s_result).replace(/%20/g,"+");
}

//url 解码
function s_decode(s_result) {
    return decodeURIComponent(js_decode(s_result));
}

function getWindowSize() {
    //获取窗口宽度
    if (window.innerWidth) { //兼容火狐，谷歌,safari等浏览器
        winWidth = window.innerWidth;
    } else if ((document.body) && (document.body.clientWidth)) { //兼容IE浏览器
        winWidth = document.body.clientWidth;
    }

    //获取窗口高度
    if (window.innerHeight) {
        winHeight = window.innerHeight;
    } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
    }
}

function getIP() {
    var a = window.location.href.replace("http://", "");
    var a_ary = a.substring(0, a.indexOf("/")).split(':');
    return a_ary[0];
}

//GUID随机码
function GUID() {
    this.date = new Date();
    /* 判断是否初始化过，如果初始化过以下代码，则以下代码将不再执行，实际中只执行一次 */
    if (typeof this.newGUID != 'function') {
        /* 生成GUID码 */
        GUID.prototype.newGUID = function () {
            this.date = new Date();
            var guidStr = '';
            sexadecimalDate = this.hexadecimal(this.getGUIDDate(), 16);
            sexadecimalTime = this.hexadecimal(this.getGUIDTime(), 16);
            for (var i = 0; i < 9; i++) {
                guidStr += Math.floor(Math.random() * 16).toString(16);
            }
            guidStr += sexadecimalDate;
            guidStr += sexadecimalTime;
            while (guidStr.length < 32) {
                guidStr += Math.floor(Math.random() * 16).toString(16);
            }
            return this.formatGUID(guidStr);
        }
        /* * 功能：获取当前日期的GUID格式，即8位数的日期：19700101 * 返回值：返回GUID日期格式的字条串 */
        GUID.prototype.getGUIDDate = function () {
            return this.date.getFullYear() + this.addZero(this.date.getMonth() + 1) + this.addZero(this.date.getDay());
        }
        /* * 功能：获取当前时间的GUID格式，即8位数的时间，包括毫秒，毫秒为2位数：12300933 * 返回值：返回GUID日期格式的字条串 */
        GUID.prototype.getGUIDTime = function () {
            return this.addZero(this.date.getHours()) + this.addZero(this.date.getMinutes()) + this.addZero(this.date.getSeconds()) + this.addZero(parseInt(this.date.getMilliseconds() / 10));
        }
        /* * 功能: 为一位数的正整数前面添加0，如果是可以转成非NaN数字的字符串也可以实现 * 参数: 参数表示准备再前面添加0的数字或可以转换成数字的字符串 * 返回值: 如果符合条件，返回添加0后的字条串类型，否则返回自身的字符串 */
        GUID.prototype.addZero = function (num) {
            if (Number(num).toString() != 'NaN' && num >= 0 && num < 10) {
                return '0' + Math.floor(num);
            } else {
                return num.toString();
            }
        }
        /*  * 功能：将y进制的数值，转换为x进制的数值 * 参数：第1个参数表示欲转换的数值；第2个参数表示欲转换的进制；第3个参数可选，表示当前的进制数，如不写则为10 * 返回值：返回转换后的字符串 */
        GUID.prototype.hexadecimal = function (num, x, y) {
            if (y != undefined) {
                return parseInt(num.toString(), y).toString(x);
            } else {
                return parseInt(num.toString()).toString(x);
            }
        }
        /* * 功能：格式化32位的字符串为GUID模式的字符串 * 参数：第1个参数表示32位的字符串 * 返回值：标准GUID格式的字符串 */
        GUID.prototype.formatGUID = function (guidStr) {
            var str1 = guidStr.slice(0, 8),
            str2 = guidStr.slice(8, 12),
            str3 = guidStr.slice(12, 16),
            str4 = guidStr.slice(16, 20),
            str5 = guidStr.slice(20);
            return guidStr.toUpperCase(); //(str1 + str2 + str3 + str4 + str5).toUpperCase();
        }
    }
}

//时间或日期相加
function DateAdd(interval, number, date) {
    switch (interval) {
    case "y": {
            date.setFullYear(date.getFullYear() + number);
            return date;
            break;
        }
    case "q": {
            date.setMonth(date.getMonth() + number * 3);
            return date;
            break;
        }
    case "M": {
            date.setMonth(date.getMonth() + number);
            return date;
            break;
        }
    case "w": {
            date.setDate(date.getDate() + number * 7);
            return date;
            break;
        }
    case "d": {
            date.setDate(date.getDate() + number);
            return date;
            break;
        }
    case "H": {
            date.setHours(date.getHours() + number);
            return date;
            break;
        }
    case "m": {
            date.setMinutes(date.getMinutes() + number);
            return date;
            break;
        }
    case "s": {
            date.setSeconds(date.getSeconds() + number);
            return date;
            break;
        }
    default: {
            date.setDate(date.getDate() + number);
            return date;
            break;
        }
    }
}

//读取TemplateIFaceLinkMenu.json对象内容
function ReadTemplateIFaceLinkMenu(objResult)
{
    jsonTemplateIFaceLinkMenu = objResult;	
}

//读取 业务.json对象内容
function ReadTemplateIFaceLinkPage(objResult)
{
    jsonTemplateIFaceLinkPage = objResult;	
}

//读取commonres.json对象内容
function ReadCommonRes(objResult)
{
	jsonReadCommonRes = objResult;
}

//设置模板参数值替换
// template_obj:模板对象(参见template_tag.js)
// template_name:模板名字符串(参见TemplateIFaceLink.json)
// interface_name:接口返回对象名字符串(参见jsData.js)
function set_template_menu(template_obj,template_name,obj,interface_name){
	var template_temp = template_obj;
	for(var key in jsonTemplateIFaceLinkMenu[interface_name][template_name])
	{
		var temColumnName = key.toString();//GetTemplateIFaceResult(interface_name,template_name,key);
		var columnName = jsonTemplateIFaceLinkMenu[interface_name][template_name][key];
		var temColumnValue = ""
		if(typeof(jsonTemplateIFaceLinkMenu[interface_name][interface_name+"_ENCODE"]) != "undefined" && 
		  typeof(jsonTemplateIFaceLinkMenu[interface_name][interface_name+"_ENCODE"][columnName]) != "undefined" &&
			jsonTemplateIFaceLinkMenu[interface_name][interface_name+"_ENCODE"][columnName].toString() == "1")
			temColumnValue = s_decode(obj[columnName]);
		else
			temColumnValue = obj[columnName];
		template_temp = template_temp.toString().replaceAll(temColumnName,temColumnValue);
	}
	return template_temp;
}

//设置模板参数值替换
// template_obj:模板对象(参见template_tag.js)
// template_name:模板名字符串(参见TemplateIFaceLink.json)
// interface_name:接口返回对象名字符串(参见jsData.js)
function set_template(template_obj,template_name,obj,interface_name){
	var template_temp = template_obj;
	for(var key in jsonTemplateIFaceLinkPage[interface_name][template_name])
	{
		var temColumnName = key.toString();//GetTemplateIFaceResult(interface_name,template_name,key);
		var columnName = jsonTemplateIFaceLinkPage[interface_name][template_name][key];
		var temColumnValue = ""
		if(columnName == "")
			temColumnValue = "";
		else 
			if(typeof(jsonTemplateIFaceLinkPage[interface_name][interface_name+"_ENCODE"]) != "undefined" && 
		  typeof(jsonTemplateIFaceLinkPage[interface_name][interface_name+"_ENCODE"][columnName]) != "undefined" &&
			jsonTemplateIFaceLinkPage[interface_name][interface_name+"_ENCODE"][columnName].toString() == "1")
			temColumnValue = s_decode(obj[columnName]);
		else
			temColumnValue = obj[columnName];
		template_temp = template_temp.toString().replaceAll(temColumnName,temColumnValue);
	}
	return template_temp;
}

//标准数据提交
function get_ajax_baseurl(inputData,inputjsonpCallBack)
{
	if(is_history_back == 0){
	    ly_index = layer.load();
		$.ajax({
			type: "POST",
			async: false,
			url: baseUrl,
			data: inputData,
			//跨域请求的URL
			dataType: "jsonp",
			jsonp: "jsoncallback",
			jsonpCallback: inputjsonpCallBack,
			success: function (data) {
				localStorage.setItem(getPageUrl()+inputjsonpCallBack.toString(), JSON.stringify(data));
				//alert("b1:"+data);
			},
			error: function () {
				layer.close(ly_index);
				swal({
					title: "告警",
					text: "网络异常或系统故障，请刷新页面！",
					type: "warning",
					showCancelButton: true,
					confirmButtonColor: "#DD6B55",
					confirmButtonText: "刷新",
					closeOnConfirm: false
				},
				function () {
					layer.close(ly_index);
					window.location.reload();
				});
			},
			// 请求完成后的回调函数 (请求成功或失败之后均调用)
			complete: function (XMLHttpRequest, textStatus) {
				$("#doing").empty();
				$("#doing").attr("style", "display:none");
			}
		});
	}else if(is_history_back == 1){
		var storage = localStorage.getItem(getPageUrl()+inputjsonpCallBack.toString());
		if (storage != null) {
			ly_index = layer.load();
			var data = JSON.parse(storage);
			callbackFuction(inputjsonpCallBack,data);
		}
	}
}

//回调函数
function callbackFuction(callback,data) {
	eval(callback+"(data)"); 
}

/***********left和bottom菜单扩展***********/
function bind_expand() {
	$('nav.menu ul.main-menu>li>a').on('click', function(e){
		var that = $(this);
		if (that.parent().find('ul:first').length)
		{
			e.preventDefault();
			if (!that.parent().hasClass('active'))
			{
				$('nav.menu ul.main-menu ul').slideUp('fast',function(){
					$('nav.menu ul.main-menu > li').removeClass('active');
				});				
				$('nav.menu ul li a span').removeClass('fa-angle-up').addClass('fa-angle-down');				
				that.parent().find('ul:first').slideDown('fast',function(){
					that.parent().addClass('active');
				});

				that.find('span').removeClass('fa-angle-down').addClass('fa-angle-up');
			}
			else
			{
				
				that.parent().find('ul:first').slideUp('fast',function(){
					$(this).parent().removeClass('active');
				});
				that.find('span').removeClass('fa-angle-up').addClass('fa-angle-down');
			}
		}
		else
		{
			$('nav.menu ul.main-menu ul').slideUp('fast');
			$('nav.menu ul.main-menu > li').removeClass('active');
			that.parent().addClass('active');
		}
	});
}

//加载bottom菜单结果
function init_result(input)
{
	if(input == null)
		return true;
    data = input.T01_sel_t_app_menu_bottom;
    $.each(data,function (i, obj)
    {
		if(i != 2){
			var template_temp = set_template_menu(tagBottomMenu_template,"tagBottomMenu_template",obj,"T01_sel_t_app_menu_bottom");
			$("#tagBottomMenu").append(template_temp);
		}
		else if(i == 2){
			var template_temp = set_template_menu(tagBottomMenu_middle_template,"tagBottomMenu_middle_template",obj,"T01_sel_t_app_menu_bottom");
			$("#tagBottomMenu").append(template_temp);
		}
    });
    layer.close(ly_index);
	T01_sel_t_app_menu_left();
}

//加载left菜单
function T01_sel_t_app_menu_left() {
	if(jsonReadCommonRes != null && typeof(jsonReadCommonRes) != "undefined" && jsonReadCommonRes.hasOwnProperty("T01_sel_t_app_menu_bottom"))
	{
			T01_sel_t_app_menu_left_result(jsonReadCommonRes);
	}
	else
	{
		var inputdata = {param_name:"T01_sel_t_app_menu_left"};
		get_ajax_baseurl(inputdata,"T01_sel_t_app_menu_left_result");
	}
}

//加载left菜单结果
function T01_sel_t_app_menu_left_result(input)
{
    data = input.T01_sel_t_app_menu_left;
    $.each(data,function (i, obj)
    {
		if(obj.parent_id == "0" && obj.count1 == ""){
			var template_temp = set_template_menu(tagMenu_template,"tagMenu_template",obj,"T01_sel_t_app_menu_left");
			$("#tagMenu").append(template_temp);
		}
		else if(obj.parent_id == "0" && obj.count1 != ""){
			var template_temp = set_template_menu(tagMenu_template2,"tagMenu_template2",obj,"T01_sel_t_app_menu_left");
			$("#tagMenu").append(template_temp);
		}
		else if(obj.parent_id != "0"){
			var template_temp = set_template_menu(tagMenu_template3,"tagMenu_template3",obj,"T01_sel_t_app_menu_left");
			$("#tagMenu ul").last().append(template_temp);
		}
    });
	bind_expand();
	layer.close(ly_index);
	//函数回调
	biz_start();
}

//页面跳转,第一个参数为url,其他为url参数
function url_load()
{
	var urlPath = "";
	if(arguments.length >=3)
	{
		for (var i = 0; i < arguments.length; i++) {
			if(i == 0 && arguments[0].length > 0)
				urlPath = arguments[0];
			else if(i == 1 && arguments[0].length == 0 && arguments[1].length > 0)
				urlPath = arguments[1];
			else if(i == 2 && urlPath.indexOf("?") == -1)
				urlPath += "?objparam_value"+(i-1).toString()+"="+s_encode(arguments[i]);
			else if(i >= 2)
				urlPath += "&objparam_value"+(i-1).toString()+"="+s_encode(arguments[i]);			
		}
		
		if(urlPath != "")
			window.location.href = urlPath;
	}
}

//加载模态对话框
function popup()
{
}